import Vue from 'vue'
import VueRouter from 'vue-router'
import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { ACCESS_TOKEN, INDEX_MAIN_PAGE_PATH } from '@/store/mutation-types'
import { generateIndexRouter } from '@/utils/util'

NProgress.configure({ showSpinner: false }) // NProgress Configuration
let env = process.env.NODE_ENV;
const whiteList = ['/user/login', '/user/register', '/user/register-result', '/user/alteration', '/user/sso/login'] // no redirect whitelist

router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  if (Vue.ls.get(ACCESS_TOKEN)) {
    /* has token */
    if (to.path === '/user/login') {
      next({ path: INDEX_MAIN_PAGE_PATH })
      NProgress.done()
    } else if (to.path === '/user/sso/login') {
      store.dispatch('Logout').then(() => {
        console.log('先退出当前登录账户，再执行SSO登录')
      })
      let params = {
        ticket: to.query.ticket,
        redirect: to.query.redirect,
      }
      store
        .dispatch('SSOLogin', params)
        .then((res) => {
          //this.departConfirm(res)
          if (res.success) {
            next({ path: params.redirect })
            NProgress.done()
          }
        })
        .catch((err) => {

          console.log(err)
          //that.requestFailed(err);
        })
    } else {
      if (store.getters.permissionList.length === 0) {
        store
          .dispatch('GetPermissionList')
          .then((res) => {

            const menuData = res.result.menu
            //console.log(res.message)
            if (menuData === null || menuData === '' || menuData === undefined) {
              return
            }
            let constRoutes = []
            constRoutes = generateIndexRouter(menuData)
            // 添加主界面路由
            store.dispatch('UpdateAppRouter', { constRoutes }).then(() => {
              // 根据roles权限生成可访问的路由表
              // 动态添加可访问路由表
              router.addRoutes(store.getters.addRouters);
              const redirect = decodeURIComponent(from.query.redirect || to.path)
              if (to.path === redirect) {
                // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
                next({ ...to, replace: true })
              } else {
                // 跳转到目的路由
                next({ path: redirect })
              }
            })
          })
          .catch((e) => {
            /* notification.error({
              message: '系统提示',
              description: '请求用户信息失败，请重试！'
            })*/

            store.dispatch('Logout').then(() => {
              next({ path: '/user/login', query: { redirect: to.fullPath } })
            })
          })
      } else if (/online/.test(to.path) && !checkLazyCompnentStatus() && env === 'prod') {
        store
          .dispatch('GetPermissionList')
          .then((res) => {
            const menuData = res.result.menu
            //console.log(res.message)
            if (menuData === null || menuData === '' || menuData === undefined) {
              return
            }
            let constRoutes = generateIndexRouter(menuData)
            const temp = constRoutes[0].children.filter(e => { return /online/.test(e.path) })[0]
            // 添加主界面路由
            require.ensure([], function () {
              const antdOnlineMini = require('@jeecg/antd-online-mini');
              temp.children.forEach(item => {
                let componentPath
                if (item.path == "/online/cgform") {
                  componentPath = antdOnlineMini.default.OnlCgformHeadList
                } else if (/copyform/.test(item.path)) {
                  componentPath = antdOnlineMini.default.OnlCgformCopyList
                } else if (item.path == "/online/cgformList/6e63e9a3b0ed4c358250f470f99e106a") {
                  componentPath = antdOnlineMini.default.OnlCgformAutoList
                } else if (/cgformTreeList/.test(item.path)) {
                  componentPath = antdOnlineMini.default.OnlCgformTreeList
                } else if (/cgformErpList/.test(item.path)) {
                  componentPath = antdOnlineMini.default.OnlCgformErpList
                } else if (/cgformTabList/.test(item.path)) {
                  componentPath = antdOnlineMini.default.OnlCgformTabList
                } else if (/cgformInnerTableList/.test(item.path)) {
                  componentPath = antdOnlineMini.default.OnlCgformInnerTableList
                } else if (item.path === '/online/cgreport') {
                  componentPath = antdOnlineMini.default.OnlCgreportHeadList
                } else if (item.path === '/online/cgformList/93d6b4aecdb541e1bcd09d6569676e44') {
                  componentPath = antdOnlineMini.default.OnlCgreportAutoList
                }
                item.component = componentPath;
              })

              store.dispatch('UpdateAppRouter', { constRoutes }).then(() => {
                // 根据roles权限生成可访问的路由表
                // 动态添加可访问路由表
                router.matcher = new VueRouter({
                  mode: "history",
                  routes: store.getters.addRouters
                }).matcher //zyq 重置路由matcher，使用新route               
                next({ ...to, replace: true })
                // const redirect = decodeURIComponent(from.query.redirect || to.path)
                // if (to.path === redirect) {
                //   next({ ...to, replace: true })
                // } else {
                //   // 跳转到目的路由
                //   next({ path: redirect })
                // }
              })
            })
          })
          .catch((e) => {
            /* notification.error({
              message: '系统提示',
              description: '请求用户信息失败，请重试！'
            })*/
            store.dispatch('Logout').then(() => {
              next({ path: '/user/login', query: { redirect: to.fullPath } })
            })
          })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      if (to.path == '/user/sso/login') {
        let params = {
          ticket: to.query.ticket,
          redirect: to.query.redirect,
        }
        store
          .dispatch('SSOLogin', params)
          .then((res) => {
            //this.departConfirm(res)
            if (res.success) {
              next({ path: params.redirect })
              NProgress.done()
            }
          })
          .catch((err) => {
            console.log(err)
            //that.requestFailed(err);
          })
      } else {
        // 在免登录白名单，直接进入

        next()
      }
    } else {
      next({ path: '/user/login', query: { redirect: to.fullPath } })
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})

function checkLazyCompnentStatus() {
  let routes = router.getRoutes()
  const temp = routes.filter(e => { return '/online/cgform' === e.path })[0];
  if (temp.components.default === undefined || temp.components.default === null) {
    return false
  }
  return true;
}
router.afterEach(() => {
  NProgress.done() // finish progress bar
})
